<?php declare(strict_types=1);
/**
 * This file is part of Swoft.
 *
 * @link https://swoft.org
 * @document https://swoft.org/docs
 * @contact group@swoft.org
 * @license https://github.com/swoft-cloud/swoft/blob/master/LICENSE
 */

namespace App\Rpc\Service;

use App\Lib\Error\Response;
use App\Rpc\Lib\Permission;
use App\Rpc\Traits\Service\ApiTrait;
use App\Rpc\Traits\Service\CommonTrait;
use App\Rpc\Traits\Service\UserBigTrait;
use App\Rpc\Traits\Service\UserCarrierTrait;
use App\Rpc\Traits\Service\TenantTrait;
use Swoft\Db\DB;
use Swoft\Rpc\Server\Annotation\Mapping\Service;
use App\Rpc\Traits\Service\RoleTrait;
use App\Rpc\Traits\Service\PermissionTrait;
use App\Rpc\Traits\Service\OrganizationTrait;
use App\Rpc\Traits\Service\PositionTrait;
use App\Rpc\Traits\Service\UserTrait;
use App\Rpc\Traits\Service\UserCaptainTrait;
use App\Rpc\Traits\Service\UserDriverTrait;
use App\Rpc\Traits\Service\UserConsignerTrait;
use Swoft\Validator\Exception\ValidatorException;

/**
 * 权限模块 - 账号模块
 * Class PermissionService - This is an controller for handle rpc request
 *
 * @since 2.0
 *
 * @Service(version="1.0")
 */
class PermissionService implements Permission
{
    use CommonTrait,
        RoleTrait,
        PermissionTrait,
        OrganizationTrait,
        PositionTrait,
        UserTrait,
        TenantTrait,
        UserCarrierTrait,
        UserCaptainTrait,
        UserDriverTrait,
        UserConsignerTrait,
        UserBigTrait,
        ApiTrait;

    /**
     * 数据库迁移
     * @param array $data
     * @return array
     */
    public function migrate(array $data): array
    {
        try{
            $data_base = $data['database']??null;
            if(!$data_base){
                throw new ValidatorException(4002, '请求参数database不合法');
            }

            //获取默认数据库
            $defaultDb = DB::connection()->getDb();
            $db_name = env('APP_ENV')."_".$defaultDb."_".$data['database'];
            $is_has_databse = is_has_database($db_name);

            if(!$is_has_databse){
                //创建数据库
                create_database($db_name);
            }

            $migrate_up = config('service.migrate_up');
            $migrate_up = explode(',', $migrate_up);

            foreach ($migrate_up as $item) {
                //接下来跑数据库迁移脚本
                $result = mMigrate('up', ['name' => $item, 'db' => $db_name]);
            }
            return Response::Info(['state' => true]);
        }catch (\Exception $e){
            return Response::FatalError($e->getCode(), $e->getMessage());
        }
    }
}
